package cn.samehope.pet.web.animal;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.samehope.pet.Consts;
import cn.samehope.pet.interceptor.WxInterceptor;
import cn.samehope.pet.interceptor.WxJsSdkInterceptor;
import cn.samehope.pet.model.PetAnimal;
import cn.samehope.pet.util.FileUtil;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.Ret;

/**
 * 宠物Controller
 * @author LD
 *
 */
public class PetAnimalController extends Controller{

	static PetAnimalService srv = PetAnimalService.me;
	
	public void index(){
		String openId = getPara("open_id");
		List<PetAnimal> list = srv.find(openId);
		//setAttr("list", list);
		renderJson(list);
	}
	
	public void save(){
		PetAnimal pa = getModel(PetAnimal.class);
		boolean flag = false;
		if(null != pa){
			Date d = new Date();
			if(null != pa.getId()){
				PetAnimal e = srv.findById(pa.getId());
				pa.setCreateDate(e.getCreateDate());
				pa.setDelFlag(e.getDelFlag());
				pa.setUpdateDate(d);
				flag = srv.update(pa);
			}else{
				pa.setOpenId((String)getSessionAttr("open_id_session"));
				pa.setCreateDate(d);
				pa.setDelFlag("0");
				pa.setUpdateDate(d);
				flag = srv.save(pa);
			}
		}
		Ret ret;
		if(flag){
			ret = Ret.ok();
		}else{
			ret = Ret.fail();
		}
		renderJson(ret);
	}
	
	@Before({WxInterceptor.class, WxJsSdkInterceptor.class})
	public void forward(){
		String id = getPara("id");
		PetAnimal pa = new PetAnimal();
		pa = srv.findById(id);
		
		setAttr("petAnimal", pa);
		render("animal_detail.html");
	}
	
	public void del(){
		int id = getParaToInt("id");
		PetAnimal pa = new PetAnimal();
		pa.setId(id);
		boolean flag = srv.delete(pa);
		Ret ret;
		if(flag){
			ret = Ret.ok();
		}else{
			ret = Ret.fail();
		}
		renderJson(ret);
	}
	
	public void saveImages() {
        String mediaId = getPara("mediaId", "");
        String fileName = System.currentTimeMillis()+"";
        String filePath = FileUtil.saveImageToDisk(Consts.picPath , fileName, mediaId);
        LogKit.info("----------fileName------"+filePath);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("filePath", filePath);
        map.put("fileName", fileName);
        renderJson(map);
	}
}
